<template>
    <el-upload
        class="upload-demo"
        ref="upload"
        action=""
        :show-file-list="false"
        :accept="accept"
        :on-change="handleChange"
        :on-success="handleSuccess"
        :before-upload="_beforeUpload"
        :http-request="_httpRequest">
        <template v-if="$slots">
            <slot></slot>
        </template>
        <el-button v-else size="small" type="primary">点击上传</el-button>
    </el-upload>
</template>

<script lang="ts">
import { Component, Prop, Vue } from "vue-property-decorator";

@Component
export default class UpLoadNormal extends Vue {
    @Prop({ type: String, default: "" }) action!: string

    @Prop({
        type: Function,
        default: () => {
            return Promise.resolve(true);
        }
    })
    readonly beforeUpload!: any;

    @Prop({
        type: String,
        default: () => {
            return "*";
        }
    })
    readonly accept!: any;

    @Prop({
        type: Boolean,
        default: () => {
            return false;
        }
    })
    readonly isSingle!: boolean;

    fileList: any[] = []

    async handleSuccess(res: any) {
        if (this.isSingle) this.fileList = [];
        this.$emit("onSuccess", res);
    }

    handleChange(file: any) {
        if (file.status === "ready") {
            this.fileList.push(file.raw);
        }
    }

    _beforeUpload() {
        this.beforeUpload().then((r: boolean) => {
            if (r) {
                return true;
            }
        });
    }

    _httpRequest() {
        if (this.isSingle) {
            this.$emit("httpRequest", [this.fileList[this.fileList.length - 1]]);
        } else {
            this.$emit("httpRequest", this.fileList);
        }
    }
}
</script>

<style lang="scss" scoped>

</style>
